//
// Created by WenDaoJiang on 2017/5/9.
// Copyright (c) 2017 文道江. All rights reserved.
//

#import "ChatVideoController.h"
#import "HybridBridge.h"
#import "ImageButton.h"
#import "AlertView.h"
#import "ServerApi.h"

@interface ChatVideoController () {
    AgoraRtcEngineKit *_engineKit;
    NSInteger _callTime;
    NSTimer *_timer;
    BOOL _enableVideo;
    BOOL _isCall;
    BOOL _isEndCall;
    NSInteger myUid;
    NSInteger fromUid;
}
@property UIView *localView;
@property UIView *remoteView;

@end

@implementation ChatVideoController


- (void)viewDidLoad {
    [super viewDidLoad];

    _enableVideo = YES;
    _isEndCall = NO;
    _isCall = _callInfo[@"isCall"] == nil ? NO : [_callInfo[@"isCall"] boolValue];

    fromUid = [_callInfo[@"from_uid"] integerValue];

    NSDictionary *info = [KVStorage getJsonValue:@"agora_signal_login_info"];
    myUid = info != nil ? [info[@"uid"] integerValue] : 0;

    // 注册挂断事件监听
    [HybridEventBus.defaultEventBus addObserver:self selector:@selector(onVideoEndCall:) name:@"agora_signal_on_end_call" object:nil];
    [HybridEventBus.defaultEventBus addObserver:self selector:@selector(onVideoEventCustomize:) name:@"agora_signal_event_customize" object:nil];
    [HybridEventBus.defaultEventBus addObserver:self selector:@selector(socketIODidDisconnect) name:@"socketIODidDisconnect" object:nil];

    [self drawComponents];

    [self initEngine];
}

- (void)dragView:(UIPanGestureRecognizer *)sender {
    CGPoint translation = [sender translationInView:self.view];

    CGRect rect = CGRectMake(_localView.frame.size.width / 2,
            _localView.frame.size.height / 2,
            self.view.frame.size.width - _localView.frame.size.width / 2,
            self.view.frame.size.height - _localView.frame.size.height / 2);

    CGFloat x = _localView.center.x + translation.x;
    CGFloat y = _localView.center.y + translation.y;

    _localView.center = CGPointMake(x < rect.origin.x ? rect.origin.x : (x > rect.size.width ? rect.size.width : x),
            y < rect.origin.y ? rect.origin.y : (y > rect.size.height ? rect.size.height : y));
    [sender setTranslation:CGPointZero inView:self.view];
}

- (void)drawComponents {
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;

    // 设置背景
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_call_bg.png"]];
    imgView.frame = self.view.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view insertSubview:imgView atIndex:0];

    UILabel *audioTips = [self makeLabel:@"语音面试中" fontSize:14 Top:0 Width:200];
    audioTips.center = CGPointMake(width / 2, height / 2);
    audioTips.tag = 3119;
    [self.view addSubview:audioTips];

    // 远程视频显示View
    _remoteView = [[UIView alloc] initWithFrame:self.view.frame];
    _remoteView.backgroundColor = [UIColor grayColor];
    _remoteView.layer.zPosition = 0;
    [self.view addSubview:_remoteView];

    // 本地视频显示View
    _localView = [[UIView alloc] initWithFrame:CGRectMake(width - width / 4 - 30, 30, width / 4, height / 4)];
    _localView.backgroundColor = [UIColor blackColor];
    _localView.layer.zPosition = 1;
    [self.view addSubview:_localView];

    _localView.hidden = YES;
    _remoteView.hidden = YES;

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragView:)];
    [_localView addGestureRecognizer:pan];


    UILabel *callTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    callTimeLabel.center = CGPointMake(width / 2, 50);
    callTimeLabel.text = @"00:00";
    callTimeLabel.textColor = UIColor.whiteColor;
    callTimeLabel.textAlignment = NSTextAlignmentCenter;
    callTimeLabel.tag = 3120;
    [self.view addSubview:callTimeLabel];

    /* 音视频切换 */
    ImageButton *enableVideoButton = [ImageButton buttonWithType:UIButtonTypeCustom];
    [enableVideoButton setTitle:@"视频" forState:UIControlStateNormal];
    [enableVideoButton setImage:[UIImage imageNamed:@"video_turn_on_camera.png"] forState:UIControlStateNormal];
    [enableVideoButton addTarget:self action:@selector(turnCameraClick:) forControlEvents:UIControlEventTouchUpInside];

    enableVideoButton.frame = CGRectMake(20, 40, 44, 64);
    enableVideoButton.imageSize = CGSizeMake(44, 44);
    enableVideoButton.tag = 3213;

    [self.view addSubview:enableVideoButton];

    /* 切换摄像头 */
    ImageButton *switchCameraButton = [ImageButton buttonWithType:UIButtonTypeCustom];
    [switchCameraButton setTitle:@"切换" forState:UIControlStateNormal];
    [switchCameraButton setImage:[UIImage imageNamed:@"video_switch_camera.png"] forState:UIControlStateNormal];
    [switchCameraButton addTarget:self action:@selector(switchCameraClick:) forControlEvents:UIControlEventTouchUpInside];

    switchCameraButton.frame = CGRectMake(20, 120, 44, 64);
    switchCameraButton.imageSize = CGSizeMake(44, 44);
    switchCameraButton.tag = 3214;

    [self.view addSubview:switchCameraButton];

    // 不通过
    ImageButton *endCallButton = [ImageButton buttonWithType:UIButtonTypeCustom];
    if(_isCall){
        endCallButton.center = CGPointMake(width / 2, self.view.frame.size.height - 80);
        [endCallButton setTitle:@"挂断" forState:UIControlStateNormal];
        [endCallButton setImage:[UIImage imageNamed:@"video_end.png"] forState:UIControlStateNormal];
    }else{
        endCallButton.center = CGPointMake(80, self.view.frame.size.height - 80);
        [endCallButton setTitle:@"不通过" forState:UIControlStateNormal];
        [endCallButton setImage:[UIImage imageNamed:@"video_fail.png"] forState:UIControlStateNormal];
    }

    endCallButton.tag = 3333;
    [endCallButton addTarget:self action:@selector(endCallClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:endCallButton];

    if(!_isCall){
        // 通过
        ImageButton *acceptCallButton = [ImageButton buttonWithType:UIButtonTypeCustom];
        acceptCallButton.center = CGPointMake(self.view.frame.size.width - 80, self.view.frame.size.height - 80);
        [acceptCallButton setTitle:@"通过" forState:UIControlStateNormal];
        [acceptCallButton setImage:[UIImage imageNamed:@"video_pass.png"] forState:UIControlStateNormal];

        [acceptCallButton addTarget:self action:@selector(acceptCallClick:) forControlEvents:UIControlEventTouchUpInside];
        acceptCallButton.tag = 3334;
        [self.view addSubview:acceptCallButton];

        UILabel *label = [self makeLabel:@"请选择面试结果" fontSize:26 Top:acceptCallButton.frame.origin.y - 50 Width: width];
        label.tag = 3335;
        [self.view addSubview: label];
    }
}

- (UILabel *)makeLabel:(NSString *)text fontSize:(NSInteger)fontSize Top:(CGFloat)top Width:(CGFloat)width {

    UIFont *font = [UIFont systemFontOfSize:fontSize];

    CGSize strSize = CGSizeMake(width, MAXFLOAT);
    CGSize labelSize = [text boundingRectWithSize:strSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{
            NSFontAttributeName: font
    }                                     context:nil].size;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, labelSize.width, labelSize.height)];

    label.text = text;
    label.textColor = UIColor.whiteColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = font;
    label.center = CGPointMake(self.view.center.x, top);

    return label;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

// 处理按钮事件
// 不通过/挂断
- (void)endCallClick:(UIButton *)sender {
    if(_isCall){
        _isEndCall = YES;
        [self emitEndCall:@"end" data:@"0000-123"];
        [self dismissSelf];
        return;
    }

    if(_isEndCall){
        [self orderDoInterview: NO];
    }else{
        [AlertView confirmWithTitle:@"确定不通过吗？" Message:@"确定后将自动挂断视频，结束面试" CallBack:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self orderDoInterview: NO];
            }
        }];
    }

}

// 通过按钮
- (void)acceptCallClick:(UIButton *)sender {
    if(_isEndCall){
        [self orderDoInterview: YES];
    }else{
        [AlertView confirmWithTitle:@"确定通过吗？" Message:@"通过即代表同意对方按照订单要求前来上班。\n确定后将自动挂断视频，结束面试" CallBack:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self orderDoInterview: YES];
            }
        }];
    }
}

// 关闭通话 按钮
- (void)closeCallClick:(UIButton *)sender  {
    [self emitEndCall:@"close" data: @"offline"];
    [self dismissSelf];
}


// 请求服务器  => 是否通过订单
- (void)orderDoInterview:(BOOL)status {

    [self stopTirme];

    NSDictionary *body = @{
            @"userWorkerId": _callInfo[@"from_uid"],
            @"interviewBeginTime": _callInfo[@"created_at"],
            @"interviewEndTime": [NSNull null],
            @"interviewStatus": status ? @"P" : @"N",
            @"orderId": _callInfo[@"ext_data"][@"jobId"]
    };

    [self emitEndCall:status ? @"pass" : @"notPass" data:_callInfo[@"ext_data"]];

    [[ServerApi new] callProgresWithView:self.view act:@"/B/Order/Do/Interview" body:body completionHandler:^(NSDictionary *data, NSError *error) {

        if(error){
            [AlertView alertWithTitle:@"" Message:error.domain Callback:^(NSInteger b) {
                [self dismissSelf];
            }];
        }else{
            if (data != nil && data[@"interviewContent"] != nil) {
                [AlertView alertWithTitle:@"" Message:[NSString stringWithFormat:@"%@", data[@"interviewContent"]] Callback:^(NSInteger b) {
                    [self dismissSelf];
                }];
            }else{
                [self dismissSelf];
            }
        }

        NSLog(@"ajax result data: %@", data);
        if (error) NSLog(@"ajax result data: err: %@", error);
    }];
}

// 音视频切换
- (void)turnCameraClick:(ImageButton *)button {
    _enableVideo = !_enableVideo;
    if(_callInfo && _callInfo[@"sid"]){
        [HybridEventBus.defaultEventBus postData:@{
                @"sid": @([_callInfo[@"sid"] integerValue]),
                @"eventName":@"switchEnableVideo",
                @"data": @{
                        @"enableVideo": @(_enableVideo)
                }
        } Tag:@"local_event_customize"];
    }
    [self setEnableVideo];
}

// 前后摄像头切换
- (void)switchCameraClick:(ImageButton *)button {
    if(_engineKit != nil){
        [_engineKit switchCamera];
    }
}

- (void)setEnableVideo {
    if(_enableVideo){
        _localView.hidden = NO;
        _remoteView.hidden = NO;
        [_engineKit enableVideo];
        [_engineKit muteLocalVideoStream: NO];
    }else{
        _localView.hidden = YES;
        _remoteView.hidden = YES;
        [_engineKit disableVideo];
        [_engineKit muteLocalVideoStream: YES];
    }

    ImageButton *button = [self.view viewWithTag:3213];
    [button setImage:[UIImage imageNamed:_enableVideo ? @"video_turn_on_camera.png" : @"video_turn_off_camera.png"] forState:UIControlStateNormal];
    [self.view viewWithTag:3214].hidden = !_enableVideo;
}

- (void)initEngine {
    if (_engineKit == nil) {
        _engineKit = [AgoraRtcEngineKit sharedEngineWithAppId:_appID delegate:self];
    }

    [_engineKit enableVideo];

    AgoraRtcVideoCanvas *canvas = [[AgoraRtcVideoCanvas alloc] init];
    [canvas setUid:(NSUInteger) myUid];
    [canvas setRenderMode:AgoraRtc_Render_Hidden];
    [canvas setView:_localView];

    [_engineKit setupLocalVideo:canvas];

    [self joinChannel];
}

- (void)joinChannel{
    _localView.hidden = NO;
    _remoteView.hidden = NO;
    [_engineKit startPreview];
    [_engineKit joinChannelByKey:NULL channelName:_channelName info:@"" uid:(NSUInteger) myUid joinSuccess:^(NSString *channel, NSUInteger uid, NSInteger elapsed) {
        [self computedCallTime];
        [_engineKit setEnableSpeakerphone: YES];
        NSLog(@"join channel success uid: %u", uid);
    }];
}

- (void)leaveChannel{
    if (_engineKit != nil) {
        [_engineKit leaveChannel:nil];
        [_engineKit stopPreview];
        _localView.hidden = YES;
        _remoteView.hidden = YES;

        /*if(_timer != nil){
            [_timer invalidate];
            _timer = nil;
        }*/
    }
}

- (void)emitEndCall:(NSString *)typeName data:(id)data {
    _isEndCall = YES;
    if(_callInfo && _callInfo[@"sid"] != nil){
        [[HybridEventBus defaultEventBus] postData:@{
                @"sid": _callInfo[@"sid"],
                @"typeName": typeName,
                @"data": data == nil ? @{} : data,
                @"fromUid": @(myUid)
        } Tag:@"signal_emit_end_call"];
    }
}

- (void)handleTimer {
    _callTime++;
    if(_isEndCall){
        if(_callTime > 60){
            [self orderDoInterview: NO];
        }else {
            UILabel *label = [self.view viewWithTag:3228];
            if(label != nil){
                label.text = [NSString stringWithFormat:@"倒计时%02iS", 60 - _callTime];
            }
        }
    }else{
        UILabel *label = [self.view viewWithTag: 3120];
        if(label != nil){
            label.text = [NSString stringWithFormat:@"%02i:%02i", _callTime / 60, _callTime % 60];
        }
    }
}

- (void)computedCallTime {
    [self stopTirme];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
}

- (void)stopTirme{
    if(_timer != nil){
        [_timer invalidate];
        _timer = nil;
    }
}

// ------------ Agora SDK 委托 -----------

- (void)rtcEngine:(AgoraRtcEngineKit *)engine firstRemoteVideoDecodedOfUid:(NSUInteger)uid size:(CGSize)size elapsed:(NSInteger)elapsed {
    AgoraRtcVideoCanvas *canvas = [[AgoraRtcVideoCanvas alloc] init];
    [canvas setUid:uid];
    [canvas setRenderMode:AgoraRtc_Render_Hidden];
    [canvas setView:_remoteView];
    [_engineKit setupRemoteVideo:canvas];
    NSLog(@"firstRemoteVideoDecodedOfUid: %u", uid);
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraRtcUserOfflineReason)reason {
    if(uid != myUid){
        [self performSelector:@selector(didOfflineOfUid:) withObject:@(uid) afterDelay:1];
    }else{
        [self didOfflineOfUid:(NSUInteger) myUid];
    }
}

// socket 连接已断开。
- (void)socketIODidDisconnect {
    [self didOfflineOfUid:(NSUInteger) myUid];
}

- (void)didOfflineOfUid :(NSUInteger)uid{
    /*if(!_isCall && !_isEndCall){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self leaveChannel];
            // 网络错误
            [self.view viewWithTag:3119].hidden = YES;
            [self.view viewWithTag:3213].hidden = YES;
            [self.view viewWithTag:3214].hidden = YES;
            [self.view viewWithTag:3120].hidden = YES;

            if(uid == 0){
                if([self.view viewWithTag:3333] != nil)[self.view viewWithTag:3333].hidden = YES;
                if([self.view viewWithTag:3334] != nil)[self.view viewWithTag:3334].hidden = YES;
                if([self.view viewWithTag:3335] != nil)[self.view viewWithTag:3335].hidden = YES;
            }

            CGSize size = self.view.frame.size;
            UILabel *topMsg = [self makeLabel:@"由于信号不稳定，视频已中断" fontSize:22 Top:size.height / 2 - 80 Width: size.width];
            [self.view addSubview:topMsg];

            ImageButton *closeButton = [ImageButton buttonWithType:UIButtonTypeCustom];
            closeButton.center = CGPointMake(size.width / 2, size.height - 80);
            [closeButton setTitle:@"关闭通话" forState:UIControlStateNormal];
            [closeButton setImage:[UIImage imageNamed:@"video_ok.png"] forState:UIControlStateNormal];

            [closeButton addTarget:self action:@selector(closeCallClick:) forControlEvents:UIControlEventTouchUpInside];

            [self.view addSubview:closeButton];

            [self stopTirme];
            _isEndCall = YES;
        });
    }else {
        if(!_isEndCall){
            [self stopTirme];
            _isEndCall = YES;
            [self emitEndCall:@"offline" data: @(uid)];
            [self dismissSelf];
        }
    }*/

    if(_isEndCall)return;

    _isEndCall = YES;
    [self stopTirme];

    if(_isCall){
        _isEndCall = YES;
        [self emitEndCall:@"offline" data: @(uid)];
        [self dismissSelf];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self leaveChannel];
            // 网络错误
            [self.view viewWithTag:3119].hidden = YES;
            [self.view viewWithTag:3213].hidden = YES;
            [self.view viewWithTag:3214].hidden = YES;
            [self.view viewWithTag:3120].hidden = YES;

            if(uid == 0){
                if([self.view viewWithTag:3333] != nil)[self.view viewWithTag:3333].hidden = YES;
                if([self.view viewWithTag:3334] != nil)[self.view viewWithTag:3334].hidden = YES;
                if([self.view viewWithTag:3335] != nil)[self.view viewWithTag:3335].hidden = YES;
            }

            CGSize size = self.view.frame.size;
            UILabel *topMsg = [self makeLabel:@"由于信号不稳定，视频已中断" fontSize:22 Top:size.height / 2 - 80 Width: size.width];
            [self.view addSubview:topMsg];

            ImageButton *closeButton = [ImageButton buttonWithType:UIButtonTypeCustom];
            closeButton.center = CGPointMake(size.width / 2, size.height - 80);
            [closeButton setTitle:@"关闭通话" forState:UIControlStateNormal];
            [closeButton setImage:[UIImage imageNamed:@"video_ok.png"] forState:UIControlStateNormal];

            [closeButton addTarget:self action:@selector(closeCallClick:) forControlEvents:UIControlEventTouchUpInside];

            [self.view addSubview:closeButton];
        });
    }
}

// ------------ Agora SDK 委托 end -----------


// ----------- 信令 start ------------

// 收到结束命令
- (void)onVideoEndCall:(NSNotification *)notification {
    //[self dismissSelf];
    if(_isEndCall)return; //如果已经挂断就不再做其他处理

    NSString *typeName = notification.userInfo != nil ? notification.userInfo[@"typeName"] : nil;
    if(typeName != nil && ([@"offline" isEqualToString:typeName] || [@"close" isEqualToString:typeName])){
        [self didOfflineOfUid:(NSUInteger) myUid];
        return;
    }

    _isEndCall = YES;
    _callTime = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self leaveChannel];
        if(_isCall){
            [self dismissSelf];
        }else{

            // 对方已挂断的界面

            [self.view viewWithTag:3119].hidden = YES;
            [self.view viewWithTag:3213].hidden = YES;
            [self.view viewWithTag:3214].hidden = YES;
            [self.view viewWithTag:3120].hidden = YES;
            CGSize size = self.view.frame.size;
            UILabel *topMsg = [self makeLabel:@"对方已挂断视频，请处理面试结果" fontSize:22 Top:size.height / 2 - 80 Width: size.width];
            [self.view addSubview:topMsg];

            UIView *timeRect = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 220, 80)];
            timeRect.center = CGPointMake(self.view.center.x, size.height / 2);
            timeRect.layer.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.1].CGColor;
            timeRect.layer.cornerRadius = 4;

            //UILabel *timeRectText = [self makeLabel:@"倒计时60S" fontSize:30 Top:0 Width:timeRect.frame.size.width - 10];
            UILabel *timeRectText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
            timeRectText.text = @"倒计时60S";
            timeRectText.textColor = UIColor.whiteColor;
            timeRectText.textAlignment = NSTextAlignmentCenter;
            timeRectText.font = [UIFont systemFontOfSize:30];
            timeRectText.center =  CGPointMake(110, 40);
            timeRectText.tag = 3228;
            [timeRect addSubview:timeRectText];

            [self.view addSubview: timeRect];

            UILabel *timeoutMsg = [self makeLabel:@"若超时未处理，则自动默认为不通过" fontSize:18 Top:size.height / 2 + 60 Width: size.width];
            timeoutMsg.textColor = UIColor.grayColor;
            [self.view addSubview:timeoutMsg];
        }
    });
}

// 收到其他指令
- (void)onVideoEventCustomize:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    if(userInfo != nil && userInfo[@"eventName"] != nil){
        // 音视频切换
        if([@"switchEnableVideo" isEqualToString:userInfo[@"eventName"]]){
            NSDictionary *data = userInfo[@"data"];
            if(data == nil)return;
            dispatch_async(dispatch_get_main_queue(), ^{
                _enableVideo = [data[@"enableVideo"] boolValue];
                [self setEnableVideo];
            });
        }
    }
}
// ----------- 信令 end ------------

// 关闭当前界面
- (void)dismissSelf {
    if (self.navigationController != nil){
        [self.navigationController popViewControllerAnimated:NO];
    }else{
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 禁止自动锁屏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

// 恢复自动锁屏
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

//
- (void)viewDidDisappear:(BOOL)animated; {
    [self leaveChannel];
    [HybridEventBus.defaultEventBus removeObserver:self name:@"agora_signal_on_end_call" object:nil];
    [HybridEventBus.defaultEventBus removeObserver:self name:@"agora_signal_event_customize" object:nil];
    [HybridEventBus.defaultEventBus removeObserver:self name:@"socketIODidDisconnect" object:nil];

    if(_timer != nil){
        [_timer invalidate];
        _timer = nil;
    }
}

@end